package cn.qdu.controller;

import cn.qdu.model.FriendRequest;
import cn.qdu.model.User;
import cn.qdu.service.FriendService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/friend/*")
public class FriendServlet extends HttpServlet {


    private FriendService friendService = new FriendService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        if (pathInfo == null || pathInfo.equals("/")) {
            pathInfo = "/list";
        }

        switch (pathInfo) {
            case "/list":
                showFriendList(request, response, currentUser);
                break;
            case "/requests":
                showFriendRequests(request, response, currentUser);
                break;
            case "/search":
                showSearchFriends(request, response, currentUser);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        if (pathInfo == null || pathInfo.equals("/")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        switch (pathInfo) {
            case "/send":
                sendFriendRequest(request, response, currentUser);
                break;
            case "/accept":
                acceptFriendRequest(request, response, currentUser);
                break;
            case "/reject":
                rejectFriendRequest(request, response, currentUser);
                break;
            case "/remove":
                removeFriend(request, response, currentUser);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }



    private void showFriendList(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        try {
            List<User> friends = friendService.getFriends(currentUser.getUserId());
            request.setAttribute("friends", friends);
            request.getRequestDispatcher("/views/friend/friend_list.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void showFriendRequests(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        try {
            List<FriendRequest> requests = friendService.getFriendRequests(currentUser.getUserId());
            request.setAttribute("requests", requests);
            request.getRequestDispatcher("/views/friend/friend_requests.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void showSearchFriends(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        try {
            String keyword = request.getParameter("keyword");
            List<User> searchResults = null;
            List<User> recommendedFriends = null;

            if (keyword != null && !keyword.trim().isEmpty()) {
                searchResults = friendService.searchUsers(keyword, currentUser.getUserId());

                // 详细日志输出
                System.out.println("搜索关键词: " + keyword);
                if (searchResults != null) {
                    System.out.println("找到 " + searchResults.size() + " 个用户");
                    for (User user : searchResults) {
                        System.out.println("用户ID: " + user.getUserId());
                        System.out.println("昵称: " + user.getNickname());
                        System.out.println("isFriend: " + user.getIsFriend());
                        System.out.println("hasPendingRequest: " + user.getHasPendingRequest());
                        System.out.println("----------------------------------");
                    }
                } else {
                    System.out.println("搜索结果为空");
                }
            } else {
                recommendedFriends = friendService.getRecommendedFriends(currentUser.getUserId());
                System.out.println("显示推荐好友: " + (recommendedFriends != null ? recommendedFriends.size() : 0));
            }

            // 从session获取消息并移除
            HttpSession session = request.getSession();
            String message = (String) session.getAttribute("message");
            String error = (String) session.getAttribute("error");

            if (message != null) {
                request.setAttribute("message", message);
                session.removeAttribute("message");
            }
            if (error != null) {
                request.setAttribute("error", error);
                session.removeAttribute("error");
            }

            request.setAttribute("keyword", keyword);
            request.setAttribute("searchResults", searchResults);
            request.setAttribute("recommendedFriends", recommendedFriends);
            request.getRequestDispatcher("/views/friend/search_friends.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    // 完善方法实现
    private void sendFriendRequest(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        String friendId = request.getParameter("friendId");
        HttpSession session = request.getSession();

        try {
            boolean success = friendService.sendFriendRequest(currentUser.getUserId(), friendId);
            if (success) {
                session.setAttribute("message", "好友请求已发送");
            } else {
                session.setAttribute("error", "发送好友请求失败，可能已经是好友或已有待处理请求");
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("error", "系统错误: " + e.getMessage());
        }
        response.sendRedirect(request.getContextPath() + "/friend/search");
    }

    private void acceptFriendRequest(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        String friendId = request.getParameter("friendId");
        HttpSession session = request.getSession();

        try {
            boolean success = friendService.acceptFriendRequest(currentUser.getUserId(), friendId);
            if (success) {
                session.setAttribute("message", "已接受好友请求");
            } else {
                session.setAttribute("error", "接受好友请求失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("error", "系统错误: " + e.getMessage());
        }
        response.sendRedirect(request.getContextPath() + "/friend/requests");
    }

    private void rejectFriendRequest(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        String friendId = request.getParameter("friendId");
        HttpSession session = request.getSession();

        try {
            boolean success = friendService.rejectFriendRequest(currentUser.getUserId(), friendId);
            if (success) {
                session.setAttribute("message", "已拒绝好友请求");
            } else {
                session.setAttribute("error", "拒绝好友请求失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("error", "系统错误: " + e.getMessage());
        }
        response.sendRedirect(request.getContextPath() + "/friend/requests");
    }

    private void removeFriend(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        String friendId = request.getParameter("friendId");
        HttpSession session = request.getSession();

        try {
            boolean success = friendService.removeFriend(currentUser.getUserId(), friendId);
            if (success) {
                session.setAttribute("message", "好友已删除");
            } else {
                session.setAttribute("error", "删除好友失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("error", "系统错误: " + e.getMessage());
        }
        response.sendRedirect(request.getContextPath() + "/friend/list");
    }
}


